<template>
  <a-card class="rent-detail" :bordered="false" v-if="cuDetail">
    <section class="title">
      <span>租金明细报表</span>
      <a-space>
        <template v-if="editable">
          <a-popconfirm
            title="是否放弃手动修改所填的数据？"
            @confirm="onCancelConfirm"
          >
            <a-button key="btn_1"> 取消 </a-button>
          </a-popconfirm>
          <a-button key="btn_2" type="primary" @click="onSubmit">
            保存
          </a-button>
        </template>
        <template v-else>
          <a-button
            @click="onEdit('divide')"
            key="btn_3"
            v-if="cuDetail.divideCount > 0"
          >
            <template #icon>
              <EditOutlined />
            </template>
            抽成
          </a-button>
          <a-button @click="onEdit('edit')" key="btn_4">
            <template #icon>
              <FormOutlined />
            </template>
            编辑
          </a-button>
        </template>
      </a-space>
    </section>
    <section class="table">
      <a-list
        :bordered="false"
        :split="false"
        :data-source="cuDetail.list"
        size="small"
      >
        <template #header>
          <!-- 表头 -->
          <a-row class="header row-style" :gutter="12">
            <a-col :span="tableLayout.section">区间</a-col>
            <a-col :span="tableLayout.feeType">费用类型</a-col>
            <a-col :span="tableLayout.payDate">付款日</a-col>
            <a-col :span="tableLayout.unitPrice">最终单价（含税）</a-col>
            <a-col :span="tableLayout.turnover">营业额</a-col>
            <a-col :span="tableLayout.recevie">
              <span v-if="isCostContract"> 应付（含税） </span>
              <span v-else>应收（含税）</span>
            </a-col>
            <a-col :span="tableLayout.taxAmount">税额</a-col>
            <a-col :span="tableLayout.action">操作</a-col>
          </a-row>
        </template>
        <template #renderItem="{ item }">
          <a-list-item>
            <a-list
              :bordered="false"
              :split="false"
              :data-source="item.list"
              size="small"
              style="width: 100%"
            >
              <!-- 分类标题 -->
              <template #header>
                <!-- <div class="text-title">{{ item.title }}</div> -->
                <a-row
                  class="data-header"
                  type="flex"
                  justify="space-between"
                  align="middle"
                  @click="item.fold = !item.fold"
                >
                  <a-col>
                    <div class="text-title">{{ item.title }}</div>
                  </a-col>
                  <a-col class="fold">
                    <template v-if="item.fold">
                      <DownOutlined />
                      <span class="mlr-5">展开</span>
                    </template>
                    <template v-else>
                      <UpOutlined />
                      <span class="mlr-5">收起</span>
                    </template>
                  </a-col>
                </a-row>
                <a-alert
                  class="alert"
                  v-if="item.belong == 'divide' && !item.fold"
                  show-icon
                  message="录入营业额后会根据分成规则自动生成对应租期的账单。录入后不可修改，请谨慎填写!"
                />
              </template>
              <template #renderItem="{ item: listItem, index: listIndex }">
                <!-- 列表 -->
                <a-row class="row-style" :gutter="12" v-show="!item.fold">
                  <!-- 标题 -->
                  <a-col :span="tableLayout.section">
                    <template v-if="item.belong != 'bond'">
                      <a-tag color="green" class="mr-5"
                        >第{{ listItem.reportStage }}期</a-tag
                      >
                    </template>
                    <span>{{ listItem.startDate }}</span>
                    <span class="ml-2 mr-2">~</span>
                    <a-date-picker
                      v-if="
                        editing && (!listItem.mdate || !listItem.mdate.length)
                      "
                      v-model:value="listItem.endDate"
                      :valueFormat="dateFormatStr"
                      :allowClear="false"
                      :disabled-date="disabledDate"
                      style="width: 120px"
                      @change="
                        (date, dateString) =>
                          handleEndDateChange({
                            current: item,
                            dateString,
                            listItem,
                            listIndex,
                          })
                      "
                    />
                    <span v-else>{{ listItem.endDate }}</span>
                    <a-popover title="不生成">
                      <template #content>
                        <span>
                          基于合同条款，该期租金账单取自固定
                          {{ item.belong == "lease" ? "分成" : "租金" }}账单
                        </span>
                      </template>
                      <ExclamationCircleOutlined
                        v-if="listItem.is_create == false"
                        style="color: #faad14; margin-left: 4px"
                      />
                    </a-popover>
                  </a-col>
                  <!-- 费用类型 -->
                  <a-col :span="tableLayout.feeType">{{
                    listItem.costTypeDesc
                  }}</a-col>
                  <!-- 付款日 -->
                  <a-col :span="tableLayout.payDate">
                    <a-date-picker
                      v-if="editing"
                      v-model:value="listItem.payDate"
                      :valueFormat="dateFormatStr"
                      :allowClear="false"
                      :disabled-date="disabledDate"
                      style="width: 120px"
                      @change="
                        (date, dateString) =>
                          handlePayDateChange(dateString, listItem)
                      "
                    />
                    <span v-else>{{ listItem.payDate }}</span>
                  </a-col>
                  <!-- 最终单价 -->
                  <a-col :span="tableLayout.unitPrice">
                    <!-- <a-input-number
                      v-if="
                        editing &&
                        item.belong == 'lease' &&
                        (!listItem.mdate || !listItem.mdate.length)
                      "
                      v-model:value="listItem.finalTaxUnitPrice"
                      :min="0"
                      :precision="pricePoint"
                    />
                    <template v-else> -->
                    <span v-if="listItem.finalTaxUnitPrice">
                      {{ listItem.finalTaxUnitPrice + listItem.finalPriceUnit }}
                    </span>
                    <span v-else>--</span>
                    <!-- </template> -->
                  </a-col>
                  <!--  营业额-->
                  <a-col :span="tableLayout.turnover">
                    <a-input-number
                      v-if="
                        dividing &&
                        item.belong == 'divide' &&
                        (!listItem.mdate || !listItem.mdate.length)
                      "
                      v-model:value="listItem.turnover"
                      :min="0"
                      @change="handleTurnoverChange(listItem)"
                      style="width: 90%"
                    />
                    <template v-else>
                      <span
                        v-if="
                          item.belong == 'divide' &&
                          (!listItem.mdate || !listItem.mdate.length)
                        "
                      >
                        <template v-if="Number(listItem.turnover)">
                          {{ listItem.turnover + listItem.price_unit }}
                        </template>
                        <template v-else>未录入</template>
                      </span>
                      <span v-else>
                        {{
                          listItem.turnover
                            ? listItem.turnover + listItem.price_unit
                            : "--"
                        }}
                      </span>
                    </template>
                  </a-col>
                  <!-- 应收 -->
                  <a-col :span="tableLayout.recevie">
                    <a-input-number
                      v-if="
                        editing &&
                        (!listItem.mdate || !listItem.mdate.length) &&
                        listItem.takeHigh == 0
                      "
                      v-model:value="listItem.receivePrice"
                      :min="0"
                      style="width: 90%"
                    />
                    <span v-else>
                      {{ listItem.receivePrice + listItem.price_unit }}
                    </span>
                  </a-col>
                  <!-- 税额 -->
                  <a-col :span="tableLayout.taxAmount">
                    <template v-if="rate && item.belong != 'bond'">
                      <a-input-number
                        v-if="
                          editing &&
                          (!listItem.mdate || !listItem.mdate.length) &&
                          listItem.takeHigh == 0
                        "
                        v-model:value="listItem.taxAmount"
                        :min="0"
                        style="width: 90%"
                      />
                      <span v-else>
                        {{ listItem.taxAmount + listItem.price_unit }}
                      </span>
                    </template>
                    <span v-else>--</span>
                  </a-col>
                  <!-- 操作 -->
                  <a-col :span="tableLayout.action">
                    <!-- takeHigh  非分成取高条款=0  分成取高条款+未取高=1 分成取高条款+取高=2 -->
                    <a-space v-if="editing && listItem.takeHigh == 0">
                      <a-button
                        type="link"
                        @click="handleItemAdd(item, listIndex, listItem)"
                      >
                        <template #icon>
                          <PlusCircleOutlined />
                        </template>
                      </a-button>
                      <a-button
                        type="link"
                        danger
                        @click="handleItemRemove(item, listIndex)"
                      >
                        <template #icon>
                          <DeleteOutlined />
                        </template>
                      </a-button>
                    </a-space>
                    <span v-else> -- </span>
                  </a-col>
                </a-row>
                <!-- 下级列表 -->

                <a-list
                  v-show="!item.fold && listItem.mdate && listItem.mdate.length"
                  :bordered="false"
                  :split="false"
                  :data-source="listItem.mdate"
                  size="small"
                  style="width: 100%"
                >
                  <template #renderItem="{ item: subItem, index: subIndex }">
                    <a-row class="row-style" :gutter="12">
                      <a-col :span="tableLayout.section">
                        <cu-icon
                          type="org-fenzhi"
                          style="font-size: 18px"
                        ></cu-icon>
                        <span class="ml-5">{{ subItem.startDate }}</span>
                        <span class="ml-2 mr-2">~</span>
                        <a-date-picker
                          v-if="editing"
                          v-model:value="subItem.endDate"
                          :valueFormat="dateFormatStr"
                          :allowClear="false"
                          :disabled-date="disabledDate"
                          style="width: 120px"
                          @change="
                            (date, dateString) =>
                              handleEndDateChange({
                                current: item,
                                dateString,
                                listItem,
                                listIndex,
                                subItem,
                                subIndex,
                              })
                          "
                        />
                        <span v-else>{{ subItem.endDate }}</span>
                      </a-col>
                      <a-col :span="tableLayout.feeType">{{
                        subItem.costTypeDesc
                      }}</a-col>
                      <a-col :span="tableLayout.payDate">{{
                        subItem.payDate
                      }}</a-col>
                      <a-col :span="tableLayout.unitPrice">
                        <!-- <a-input-number
                          v-if="editing && item.belong == 'lease'"
                          v-model:value="subItem.finalTaxUnitPrice"
                          :min="0"
                          :precision="pricePoint"
                        />
                        <template v-else> -->
                        <span v-if="subItem.finalTaxUnitPrice">
                          {{
                            subItem.finalTaxUnitPrice + subItem.finalPriceUnit
                          }}
                        </span>
                        <span v-else>--</span>
                        <!-- </template> -->
                      </a-col>
                      <a-col :span="tableLayout.turnover">
                        <a-input-number
                          v-if="dividing && item.belong == 'divide'"
                          v-model:value="subItem.turnover"
                          :min="0"
                          @change="handleTurnoverChange(listItem, subIndex)"
                          style="width: 90%"
                        />
                        <template v-else>
                          <span v-if="item.belong == 'divide'">
                            <template v-if="Number(subItem.turnover)">
                              {{ subItem.turnover + subItem.price_unit }}
                            </template>
                            <template v-else>未录入</template>
                          </span>
                          <span v-else>--</span>
                        </template>
                      </a-col>
                      <a-col :span="tableLayout.recevie">
                        <a-input-number
                          v-if="editing"
                          :min="0"
                          v-model:value="subItem.receivePrice"
                          @change="handleReceivePriceChange(listItem)"
                          style="width: 90%"
                        />
                        <span v-else>
                          {{ subItem.receivePrice + subItem.price_unit }}
                        </span>
                      </a-col>
                      <!-- 税额 -->
                      <a-col :span="tableLayout.taxAmount">
                        <template v-if="rate && item.belong != 'bond'">
                          <a-input-number
                            v-if="editing"
                            v-model:value="subItem.taxAmount"
                            :min="0"
                            style="width: 90%"
                          />
                          <span v-else>
                            {{ subItem.taxAmount + listItem.price_unit }}
                          </span>
                        </template>
                        <span v-else>--</span>
                      </a-col>
                      <a-col :span="tableLayout.action">
                        <span> -- </span>
                      </a-col>
                    </a-row>
                  </template>
                </a-list>
              </template>
            </a-list>
          </a-list-item>
        </template>
        <template #footer>
          <a-row
            class="header row-style mt-20"
            :gutter="12"
            v-if="!hasLeaseUnit4"
          >
            <a-col :span="4" class="total-name">总计</a-col>
            <a-col :span="20" class="text-right">
              <a-space size="large">
                <span>
                  {{ isCostContract ? "费用应付总计:" : "费用应收总计:"
                  }}{{ cuDetail.receiveTotal }}元
                </span>
                <span v-if="rate">
                  税额总计： {{ cuDetail.taxAmountTotal }}元
                </span>
                <span
                  >{{
                    isCostContract ? "保证金应付总计：" : "保证金应收总计："
                  }}
                  {{ cuDetail.bondTotal }}元
                </span>
              </a-space>
            </a-col>
          </a-row>
        </template>
      </a-list>
    </section>
  </a-card>
</template>

<script>
import { defineComponent, watch, ref, computed, toRaw } from "vue";
import moment from "moment";
import {
  EditOutlined,
  FormOutlined,
  PlusCircleOutlined,
  DeleteOutlined,
  DownOutlined,
  UpOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons-vue";
import store from "../../../../store";
import { message } from "ant-design-vue";
import utils from "../../../../common/utils/utils";
import { useRoute } from "vue-router";
const tableLayout = {
  section: 6,
  feeType: 2,
  payDate: 2,
  unitPrice: 3,
  turnover: 3,
  recevie: 3,
  taxAmount: 3,
  action: 2,
};
const dateFormatStr = "YYYY-MM-DD";

export default defineComponent({
  name: "RentDetail",
  components: {
    EditOutlined,
    FormOutlined,
    PlusCircleOutlined,
    DeleteOutlined,
    DownOutlined,
    UpOutlined,
    ExclamationCircleOutlined,
  },
  props: {
    detail: {
      type: Object,
      default: () => {
        return {};
      },
    },
    type: {
      type: String,
      default: "detail",
    },
    params: {
      type: Object,
      default: () => {
        return {};
      },
    },
    trigger: {
      type: Number,
      default: 0,
    },
    paneFrom: {
      type: String,
      default: "default",
    },
  },
  setup(props, context) {
    const contractDateRange = computed(() => store.getters.contractDateRange);
    const disabledDate = (current) => {
      const { startDate, endDate } = contractDateRange.value;
      return (
        current < moment(startDate).startOf("day") ||
        current > moment(endDate).endOf("days")
      );
    };

    // compute_lease unit1 固定租金 unit2 固定分成 unit3 租金+分成 unit4 租金/分成取高
    const hasLeaseUnit4 = computed(() => {
      const { leaseTerms } = props.params;
      if (leaseTerms) {
        for (let item of leaseTerms) {
          if (item.compute_lease == "unit4") {
            return true;
          }
        }
      }

      return false;
    });

    // 税率
    const rate = computed(() => {
      const { rentTaxTerms } = props.params;
      return rentTaxTerms && rentTaxTerms.taxRule == 1
        ? rentTaxTerms.taxRate
        : 0;
    });

    // 监听付款日修改
    const handlePayDateChange = (dateString, current) => {
      if (current.mdate && current.mdate.length) {
        for (let item of current.mdate) {
          item.payDate = dateString;
        }
      }
    };

    // 监听区间改变
    const handleEndDateChange = (e) => {
      const { current, dateString, listItem, listIndex, subItem, subIndex } = e;
      const currentStartDate = subItem ? subItem.startDate : listItem.startDate;
      if (moment(dateString).isBefore(currentStartDate)) {
        listItem.endDate = "";
        message.error("结束时间必须晚于开始时间~");
        return;
      }
      const nextItem = subItem
        ? listItem.mdate[subIndex + 1]
        : current.list[listIndex + 1];
      if (nextItem) {
        nextItem.startDate = moment(dateString)
          .add(1, "days")
          .format(dateFormatStr);
      } else if (subItem) {
        listItem.endDate = dateString;
        let nextListItem = current.list[listIndex + 1];
        if (nextListItem) {
          nextListItem.startDate = moment(dateString)
            .add(1, "days")
            .format(dateFormatStr);
        }
      }
    };

    // 应收金额改变
    const handleReceivePriceChange = (listItem) => {
      let receivePrice = 0;
      let is_create = true;
      for (let item of listItem.mdate) {
        if (item.receivePrice) {
          receivePrice += Number(item.receivePrice);
        } else if (is_create) {
          is_create = false;
        }
      }
      listItem.is_create = is_create;
      listItem.receivePrice = receivePrice;
    };

    const pricePoint = computed(
      () => store.getters.addFormData.basicInfo.unit_price_point || 2
    );

    // 抽成营业额改变
    const handleTurnoverChange = (listItem, subIndex = -1) => {
      const currentItem = subIndex == -1 ? listItem : listItem.mdate[subIndex];
      currentItem.group = currentItem.group || listItem.group;
      const { leaseTerms } = props.params;
      const ratioInfo = utils.getDivideRatio(leaseTerms, currentItem);
      console.log("-----------handleTurnoverChange ratioInfo", ratioInfo);
      if (ratioInfo) {
        const result = utils.getRatioPrice(currentItem, ratioInfo, rate.value);
        currentItem.receivePrice = result.receivePrice;
        currentItem.taxAmount = result.taxAmount;
        utils.setReceviePrice({
          leaseList: cuDetail.value.list,
          currentItem: listItem,
          subIndex,
          canZero: false,
        });
        console.log(
          "-----------handleTurnoverChange receivePrice",
          currentItem.receivePrice,
          currentItem.taxAmount
        );
      }
    };

    // 添加条项
    const handleItemAdd = (current, index, currentItem) => {
      const newItem = {
        ...currentItem,
        mdate: [],
        startDate: currentItem.endDate || contractDateRange.value.startDate,
        endDate: "",
        reportStage: currentItem.reportStage + 1,
        receivePrice: 0,
        taxAmount: 0,
      };
      newItem.startDate = moment(newItem.startDate)
        .add(1, "days")
        .format(dateFormatStr);
      current.list.splice(index + 1, 0, newItem);
      current.list.forEach((it, i) => {
        if (i > index + 1) {
          it.reportStage++;
        }
      });
    };

    // 删除条项
    const handleItemRemove = (current, index) => {
      current.list.splice(index, 1);
      current.list.forEach((it, i) => {
        if (i > index - 1) {
          it.reportStage--;
        }
      });
    };

    // 编辑状态
    const editable = ref(false);
    const editType = ref("");
    const onEdit = (type) => {
      editType.value = type;
      editable.value = true;
    };
    const editing = computed(() => editType.value == "edit" && editable.value);
    const dividing = computed(
      () => editType.value == "divide" && editable.value
    );

    // 取消编辑
    const onCancelConfirm = () => {
      cuDetail.value = lastDetail
        ? JSON.parse(JSON.stringify(lastDetail))
        : JSON.parse(JSON.stringify(props.detail));
      editType.value = "";
      editable.value = false;
    };

    // 保存
    let lastDetail = null;
    const onSubmit = () => {
      const { list } = cuDetail.value;
      let receiveTotal = 0;
      let bondTotal = 0;
      let taxAmountTotal = 0;
      for (let topList of list) {
        if (topList.list) {
          for (let listItem of topList.list) {
            if (validateItem(listItem)) {
              if (topList.belong == "bond") {
                bondTotal += Number(listItem.receivePrice);
              } else {
                if (topList.belong != "bond" && rate.value) {
                  taxAmountTotal += Number(listItem.taxAmount);
                }

                receiveTotal += Number(listItem.receivePrice);
              }
              if (listItem.mdate && listItem.mdate.length) {
                for (let subItem of listItem.mdate) {
                  if (!validateItem(subItem)) {
                    return;
                  }
                }
              }
            } else {
              return;
            }
          }
        }
      }
      const { basicInfo } = store.getters.addFormData;
      const unit_price_point = basicInfo ? basicInfo.unit_price_point : 2;
      cuDetail.value.bondTotal = Number(bondTotal).toFixed(unit_price_point);
      cuDetail.value.receiveTotal =
        Number(receiveTotal).toFixed(unit_price_point);
      cuDetail.value.taxAmountTotal =
        Number(taxAmountTotal).toFixed(unit_price_point);
      lastDetail = JSON.parse(JSON.stringify(cuDetail.value));
      // 关闭编辑
      editType.value = "";
      editable.value = false;
    };

    const validateItem = (item) => {
      // console.log("validateItemvalidateItem", item);
      if (!item.endDate) {
        message.error("请完善区间信息~");
        return false;
      }
      if (!item.payDate) {
        message.error("请完善付款时间~");
        return false;
      }
      if (!item.finalPrice && item.finalPrice != 0) {
        message.error("请填写最终单价~");
        return false;
      }
      if (!item.receivePrice && item.receivePrice != 0) {
        message.error("请填写应收金额~");
        return false;
      }
      return true;
    };

    // 明细
    const cuDetail = ref();
    watch(
      () => props.detail,
      (detail) => {
        setCuDeatil();
      }
    );

    const setCuDeatil = () => {
      const { detail } = props;
      if (Object.keys(detail).length) {
        lastDetail = null;
        editType.value = "";
        editable.value = false;
        cuDetail.value = JSON.parse(JSON.stringify(detail));
        console.log("-----------------租金明细", toRaw(cuDetail.value));
      }
    };

    const init = () => {
      setCuDeatil(true);
    };

    init();

    const handleDetailReturn = () => {
      if (cuDetail.value) {
        const currentPaneContent =
          store.getters.clauseContentList[props.paneFrom];
        if (currentPaneContent.changed) {
          context.emit("fail", {
            type: "detail",
            msg: "您更改过条款内容，当前条款租金明细需要重新生成~",
          });
          return;
        }
        const { list, receiveTotal, bondTotal, taxAmountTotal, receiveDiscount } =
          cuDetail.value;
        let detail = {
          bondData: [],
          leaseData: [],
          divideData: [],
          receiveTotal,
          bondTotal,
          taxAmountTotal,
          receiveDiscount,
        };
        list.forEach((item) => {
          if (item.belong == "bond" && item.list) {
            detail.bondData = detail.bondData.concat(item.list);
          }
          if (item.belong == "divide") {
            detail.divideData = detail.divideData.concat(item.list);
          }
          if (item.belong == "lease") {
            detail.leaseData = detail.leaseData.concat(item.list);
          }
        });
        context.emit("success", { type: "detail", content: detail });
      } else {
        context.emit("fail", { type: "detail", msg: "您还未生成租金明细" });
      }
    };

    watch(
      () => props.trigger,
      (trigger) => {
        if (trigger && props.type == "next") {
          handleDetailReturn();
        }
      }
    );

    watch(
      () => store.getters.currentStep,
      (val) => {
        if (val == 1) {
          // 修改基本信息的租赁起始日期，使条款日期超过租赁期期范围时，需要清空明细，重新手动生成
          console.log(
            "store.getters.clearRentDetail",
            store.getters.clearRentDetail
          );
          if (store.getters.clearRentDetail) {
            cuDetail.value = null;
            store.dispatch("SetClearRentDetail", false);
          }
        }
      }
    );

    const $route = useRoute();
    // 是否成本合同
    const isCostContract = computed(
      () => $route.query.contractType == "costContract"
    );

    return {
      dateFormatStr,
      tableLayout,
      editable,
      cuDetail,
      editing,
      dividing,
      hasLeaseUnit4,
      pricePoint,
      rate,
      disabledDate,
      onEdit,
      onSubmit,
      onCancelConfirm,
      handlePayDateChange,
      handleItemRemove,
      handleItemAdd,
      handleEndDateChange,
      handleReceivePriceChange,
      handleTurnoverChange,
      isCostContract,
    };
  },
});
</script>

<style lang="less" scoped>
@rowHeight: 30px;

.rent-detail {
  width: 100%;
  .title {
    width: 100%;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: rgba(0, 0, 0, 0.8);
    font-size: 18px;
    font-weight: bold;
  }
  .table {
    margin-top: 20px;
    .header {
      background-color: #f7f7f7;
    }
    .total-name {
      color: rgba(0, 0, 0, 0.8);
      font-size: 16px;
      font-weight: bold;
    }
    .row-style {
      width: 100%;
      min-height: @rowHeight;
      line-height: @rowHeight;
      padding: 10px 12px;
      vertical-align: middle;
    }
    .data-header {
      cursor: pointer;

      .fold {
        padding: 0 10px;
        color: rgba(0, 0, 0, 0.5);
      }
    }
    .alert {
      margin: 10px;
    }
    &:deep(.ant-alert) {
      padding: 4px 16px;
    }
    &:deep(.ant-list-item) {
      padding: 0px;
    }
    &:deep(.ant-list-header) {
      padding-bottom: 0px;
    }
  }
}
</style>
